package local.blueheart.data.springdatademo.util.mht;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

public class JQuery {

    private static final Logger LOGGER = LoggerFactory.getLogger(JQuery.class);

    private boolean isNeedLogin = false;

    private RequestConfig requestConfig;

    private HttpClient httpClient;

    public JQuery() {
        httpClient = HttpClients.createDefault();
        requestConfig = RequestConfig.custom().setConnectTimeout(5 * 1000).setSocketTimeout(5 * 1000).build();
    }


    public void login(String hostname, String username, String password) {
        //Domino Login
        try {
            URI uri = new URIBuilder().setScheme("http").setHost(hostname).setPath("names.nsf").setQuery("login").setParameter("username", username).setParameter("password", password).build();
            HttpGet httpget = new HttpGet(uri);
            httpget.setConfig(requestConfig);
            HttpResponse httpResponse = httpClient.execute(httpget);
            HttpEntity entity = httpResponse.getEntity();
            String resultHTML = EntityUtils.toString(entity);
            LOGGER.info("login info {}", resultHTML);
            httpget.releaseConnection();
        } catch (URISyntaxException e) {
            LOGGER.error("uri 转换出错", e);
        } catch (ClientProtocolException e) {
            LOGGER.error("客户端连接协议出错", e);
        } catch (IOException e) {
            LOGGER.error("IO异常", e);
        }

    }

    public String getHtml(String url, String strEncoding) throws IOException {
        Document document = Jsoup.parse(getDocHTML(url, strEncoding));
        //removeHref(document);
        return document.outerHtml();
    }

    private void removeHref(Document doc) {
        doc.select("a").removeAttr("href");// 去掉a的链接
        doc.select("img").removeAttr("onclick"); // 去掉图片onclick事件
        doc.select("input[type=submit]").attr("type", "button");// submit按钮改为普通按钮
        doc.select("input[type=button]").removeAttr("onclick"); // 去掉按钮的onclick事件
        doc.select("area").removeAttr("href");// 去掉area的链接
    }

    private String getDocHTML(String docUrl, String strEncoding) throws IOException {
        HttpGet get = new HttpGet(docUrl);
        get.setConfig(requestConfig);
        HttpResponse response = httpClient.execute(get);
        String content = "";
        if (strEncoding != null && "".equals(strEncoding)) {
            content = EntityUtils.toString(response.getEntity(), strEncoding);
        } else {
            content = EntityUtils.toString(response.getEntity());
        }
        get.releaseConnection();
        return content;
    }




    public byte[] downBinaryFileByJquery(String strUrl) throws IOException {
            HttpGet get = new HttpGet(strUrl);
            RequestConfig requestConfig = RequestConfig.copy(this.requestConfig).setRedirectsEnabled(true).build();
            get.setConfig(requestConfig);
            HttpResponse httpResponse = httpClient.execute(get);
            byte[] bytes = EntityUtils.toByteArray(httpResponse.getEntity());
            get.releaseConnection();
            return bytes;
    }

    public File downFile(String fileUrl,File dstFile) throws IOException {
        HttpGet get = new HttpGet(fileUrl);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5 * 10000).setSocketTimeout(5 * 10000).setRedirectsEnabled(true).build();
        get.setConfig(requestConfig);
        File downloadFile = httpClient.execute(get,new FileDownloadResponseHandler(dstFile));
        get.releaseConnection();
        return downloadFile;
    }

    static class FileDownloadResponseHandler implements ResponseHandler<File> {

        private final File target;

        public FileDownloadResponseHandler(File target) {
            this.target = target;
        }

        @Override
        public File handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            InputStream source = response.getEntity().getContent();
            FileUtils.copyInputStreamToFile(source, this.target);
            return this.target;
        }
    }



    public static void main(String[] args) throws IOException {
        JQuery jQuery = new JQuery();
        jQuery.login("devemis.jx.chinamobile.com", "admin", "1");
        //http://devemis.jx.chinamobile.com/lib/fsarchiveindex.nsf/EF1DE5BEFC1233F5482573140056FB5A/183FE45EC0354DE94825835400303DB8?OpenDocument
        String html = jQuery.getHtml("http://devemis.jx.chinamobile.com/lib/fsarchive/fsarchivestore_B5T9QH.nsf/0/C7CF6C8D7FBCCB1C4825835400303DB8?openDocument", "gb2312");
        LOGGER.info("=====================================");
        LOGGER.info(html);

    }

}


